package com.example.ujsfish.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.ujsfish.R;

import com.example.ujsfish.utils.AppNetService;
import com.example.ujsfish.model.manual.ManualControlData;
import com.example.ujsfish.model.monitor.Data;
import com.example.ujsfish.model.monitor.JsonRootBean;
import com.example.ujsfish.utils.DeviceName;
import com.example.ujsfish.utils.RetrofitManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class CmManual extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private static final String TAG = "CmManual";



    private Button cruiseBackBtn;
    private Button cmAuto;
    private Button cmSemiAutoBtn;
    private Button btn_stop;
    private Button btn_reset;
    private Button btn_park;
    private Button btn_weigh;
    private TextView currentBatteryRemain;
    private TextView remainFeed;
    private TextView text_jingdu;
    private TextView text_weidu;
    private ImageView moveForward;
    private ImageView moveBack;
    private ImageView moveLeft;
    private ImageView moveRight;
    private TextView gpsStatue;
    private TextView text_workStatue;

    private TextView text_rightWheel;
    private TextView text_leftWheel;

    private Spinner spinner_paoPan1;
    private Spinner spinner_benLiuLiang1;
    private Spinner spinner_zhenDong1;
    private Spinner spinner_yaoYeFa1;

    private String weight;

     String paoPan = "00.0";
     String zhenDong= "00.0";
     String bengLiuLiang = "00.0";
     String yaoYeFa = "00.0";

    String id;

    List<String> deviceId = new ArrayList<>();


    RetrofitManager myRetrofitManager = RetrofitManager.getInstance();
    Retrofit myRetrofit = RetrofitManager.getRetrofit();
    AppNetService appNetService = myRetrofitManager.getApiService(AppNetService.class);
    Timer timer;
    TimerTask task;
    private SharedPreferences mPreferences;


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String number = parent.getItemAtPosition(position).toString();
        System.out.println("number" + number);
        TextView tv1;
        TextView tv2;
        TextView tv3;
        TextView tv4;
        switch (parent.getId()){
            case R.id.spinner_paoPan1:
                paoPan = number;
                System.out.println("paopan" + paoPan);
                tv1 = (TextView)view;
                //tv1.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            case R.id.spinner_zhenDong1:
                zhenDong = number;
                //为了确保在振动电机开启的时候，抛盘电机是运行的，防止饵料堵塞出料口
                //即，抛盘电机先于振动电机先运行
                if("0.00".equals(paoPan) && !"0.00".equals(zhenDong) ){
                    //当振动电机开启的时候，没有手动开启抛盘电机的话，就自动给一个抛盘电机占空比
                    paoPan = zhenDong;
                    spinner_paoPan1.setSelection(2,true);
                }
                tv2 = (TextView)view;
                //tv2.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            case R.id.spinner_benLiuLiang1:
                bengLiuLiang = number;
                tv3 = (TextView)view;
                //tv3.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            case R.id.spinner_yaoYeFa1:
                yaoYeFa = number;
                tv4 = (TextView)view;
                //tv4.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            default:break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }



    //手动控制对象
    private ManualControlData manualCtrlData = ManualControlData.getInstance();
    private ManualControlData.ManualBody manualBody = ManualControlData.getManualBody();






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cm_manual_activity);

        mPreferences = getSharedPreferences("data",MODE_PRIVATE);
        if (mPreferences != null) {
            weight = mPreferences.getString("weight","00.0");
            Log.d(TAG, "weight --------->" + weight );
        }


        //初始化设备名称（ID）集合
        //deviceId.add("002200425850500C20353555");
        //deviceId.add("003900425850500C20353555");

        //DeviceName.getDeviceInstance().setDeviceId(deviceId);
        //DeviceName.getDeviceInstance().getDeviceId().add("003300425850500C20353555");
        id = DeviceName.getDeviceInstance().getDeviceId().get(0);

        initSpinner();
        initView();

        btn_park.setEnabled(false);
        btn_weigh.setEnabled(false);


//        Call<JsonRootBean> call1 = appNetService.postMonitor(id);
//        call1.enqueue(new Callback<JsonRootBean>() {
//            @Override
//            public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
//                System.out.println(response.toString());
//                JsonRootBean jsonRootBean = response.body();
//                Data monitorData = jsonRootBean.getData().get(0);
//
//                System.out.println(jsonRootBean.toString());
//                System.out.println(monitorData.toString());
//            }
//
//            @Override
//            public void onFailure(Call<JsonRootBean> call, Throwable t) {
//                Log.d(TAG, "onFailure: " + t.toString());
//            }
//        });


        btn_park.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appNetService.postParking(id).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });

        btn_weigh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appNetService.postWeigh(id).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });

        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: " + paoPan + zhenDong  + bengLiuLiang + yaoYeFa);
                manualBody.setPara(id,String.valueOf(paoPan),String.valueOf(zhenDong),String.valueOf(bengLiuLiang),String.valueOf(yaoYeFa));
                sendManualCm(id);

            }
        });


        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manualBody.clear();
                Log.d(TAG, "sendManualCm: " + manualBody.toString());
                //sendManualCm(id);
                Call<ResponseBody> call = appNetService.postStop(id);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Log.d(TAG, "onResponse: " + response);

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });

            }
        });

        //手动控制指令
        moveForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                manualBody.setLeftWheelAdd();
                manualBody.setRightWheelAdd();
                sendManualCm(id);
            }
        });

        moveBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setLeftWheelDelete();
                manualBody.setRightWheelDelete();
                sendManualCm(id);
            }
        });

        moveLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setRightWheelAdd();
                sendManualCm(id);

            }
        });

        moveRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setLeftWheelAdd();
                sendManualCm(id);
            }
        });


        //发送反航指令
        cruiseBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Call<ResponseBody> call = appNetService.postReturn(id);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Log.d(TAG, "onResponse: " + response);
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });

        cmAuto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CmManual.this, CmAuto.class);
                startActivity(intent);
            }
        });

        cmSemiAutoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CmManual.this,CmSemiAuto.class);
                startActivity(intent);
            }
        });




    }

    private void sendManualCm(String id) {
        manualBody.setDevice_name(id);
        text_leftWheel.setText(manualBody.getLeft_wheel());
        text_rightWheel.setText(manualBody.getRight_wheel());

        Log.d(TAG, "sendManualCm: " + manualBody.toString());
        Call<ResponseBody> call = appNetService.postManualControl(manualBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: " + response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }


    private void initView() {

        cruiseBackBtn = findViewById(R.id.cruiseBackBtn);
        cmAuto = findViewById(R.id.cmAuto);
        cmSemiAutoBtn = findViewById(R.id.cmSemiAutoBtn);
        btn_stop = findViewById(R.id.btn_stop1);
        btn_reset = findViewById(R.id.btn_reset1);
        btn_park = findViewById(R.id.btn_park);
        btn_weigh = findViewById(R.id.btn_weigh);

        currentBatteryRemain = findViewById(R.id.currentBatteryRemain);
        remainFeed = findViewById(R.id.remainFeed);
        moveForward = findViewById(R.id.imageView);
        moveBack = findViewById(R.id.imageView2);
        moveLeft = findViewById(R.id.imageView3);
        moveRight = findViewById(R.id.imageView4);
        gpsStatue = findViewById(R.id.gpsStatue);
        text_workStatue = findViewById(R.id.text_workStatue);
        text_jingdu =findViewById(R.id.textView_jingdu);
        text_weidu =findViewById(R.id.textView_weidu);

        text_leftWheel = findViewById(R.id.text_leftWheel);
        text_rightWheel = findViewById(R.id.text_rightWheel);



    }

    private void updateUi(AppNetService appNetService) {
        Call<JsonRootBean> call1 = appNetService.postMonitor(id);
        call1.enqueue(new Callback<JsonRootBean>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
                System.out.println(TAG + response.toString());

                if(response.body().getData().size() != 0) {
                    JsonRootBean jsonRootBean = response.body();
                    Data monitorData = jsonRootBean.getData().get(0);
                    currentBatteryRemain.setText(monitorData.getQuantity());


                    remainFeed.setText(monitorData.getClout() + " /" + weight );

                    gpsStatue.setText(monitorData.getGps());
                    text_workStatue.setText(monitorData.getStatus());
                    text_jingdu.setText(monitorData.getX_coordinate());
                    text_weidu.setText(monitorData.getY_coordinate());

                }

            }

            @Override
            public void onFailure(Call<JsonRootBean> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });

    }

    private void initSpinner() {

        spinner_paoPan1 = findViewById(R.id.spinner_paoPan1);
        spinner_zhenDong1= findViewById(R.id.spinner_zhenDong1);
        spinner_benLiuLiang1 = findViewById(R.id.spinner_benLiuLiang1);
        spinner_yaoYeFa1 = findViewById(R.id.spinner_yaoYeFa1);
        //抛盘电机
        //多种不同的模式
        List<String> data_list1 = new ArrayList<>();//data_list是一个数组列表
        data_list1.add("00.0");
        data_list1.add("10.0");
        data_list1.add("20.0");
        data_list1.add("30.0");
        data_list1.add("40.0");
        data_list1.add("50.0");
        data_list1.add("60.0");
        data_list1.add("70.0");
        data_list1.add("80.0");
        data_list1.add("90.0");
        data_list1.add("99.9");

        //适配器
        ArrayAdapter<String> arrAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list1);
        //设置样式
        arrAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_paoPan1.setAdapter(arrAdapter1);
        //为Spinner设置选中事件监听器
        spinner_paoPan1.setOnItemSelectedListener(CmManual.this);

        //振动电机
        //多种不同的模式
        List<String> data_list2 = new ArrayList<String>();//data_list是一个数组列表
        data_list2.add("00.0");
        data_list2.add("10.0");
        data_list2.add("20.0");
        data_list2.add("30.0");
        data_list2.add("40.0");
        data_list2.add("50.0");
        data_list2.add("60.0");
        data_list2.add("70.0");
        data_list2.add("80.0");
        data_list2.add("90.0");
        data_list2.add("99.9");

        //适配器
        ArrayAdapter<String> arrAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list2);
        //设置样式
        arrAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_zhenDong1.setAdapter(arrAdapter2);
        //为Spinner设置选中事件监听器
        spinner_zhenDong1.setOnItemSelectedListener(CmManual.this);

        //泵流量
        //多种不同的模式
        List<String> data_list3 = new ArrayList<String>();//data_list是一个数组列表
        data_list3.add("00.0");
        data_list3.add("10.0");
        data_list3.add("20.0");
        data_list3.add("30.0");
        data_list3.add("40.0");
        data_list3.add("50.0");
        data_list3.add("60.0");
        data_list3.add("70.0");
        data_list3.add("80.0");
        data_list3.add("90.0");
        data_list3.add("99.9");


        //适配器
        ArrayAdapter<String> arrAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list3);
        //设置样式
        arrAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_benLiuLiang1.setAdapter(arrAdapter3);
        //为Spinner设置选中事件监听器
        spinner_benLiuLiang1.setOnItemSelectedListener(CmManual.this);

        //药液阀
        //多种不同的模式
        List<String> data_list4 = new ArrayList<String>();//data_list是一个数组列表
        data_list4.add("00.0");
        data_list4.add("10.0");
        data_list4.add("20.0");
        data_list4.add("30.0");
        data_list4.add("40.0");
        data_list4.add("50.0");
        data_list4.add("60.0");
        data_list4.add("70.0");
        data_list4.add("80.0");
        data_list4.add("90.0");
        data_list4.add("99.9");



        //适配器
        ArrayAdapter<String> arrAdapter4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list4);
        //设置样式
        arrAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_yaoYeFa1.setAdapter(arrAdapter4);
        //为Spinner设置选中事件监听器
        spinner_yaoYeFa1.setOnItemSelectedListener(CmManual.this);



    }

    @Override
    protected void onResume() {
        super.onResume();

        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                updateUi(appNetService);

            }
        };
        timer.schedule(task,0,2000);
        System.out.println("定时器开启");

    }


    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
        System.out.println("定时器关闭");
    }

}